﻿using System.Collections.Generic;
using NHibernate;
using NHibernate.Linq;
using System.Linq;

namespace Scribble.Repositories
{
    public class PostRepository : IPostRepository
    {
        private readonly ISession session;

        public PostRepository(ISession session)
        {
            this.session = session;
        }

        public IList<Post> GetPosts()
        {
            return session
                .Query<Post>()
                .WithDefaultOrdering()
                .ToList();
        }

        public Post GetPost(int year, int month, string urlTitle)
        {
            return session
                .Query<Post>()
                .FirstOrDefault
                (
                    p =>
                    p.PublishDate.Year == year &&
                    p.PublishDate.Month == month &&
                    p.UrlTitle == urlTitle
                );
        }

        public IList<Post> GetPostsByTag(Tag tag)
        {
            return session
                .Query<Post>()
                .Where(p => p.Tags.Any(t => t == tag))
                .WithDefaultOrdering()
                .ToList();
        }

        public IList<Post> GetPostsByCategory(Category category)
        {
            return session
                .Query<Post>()
                .Where(p => p.Category == category)
                .WithDefaultOrdering()
                .ToList();
        }
    }

    public static class QueryableExtensions
    {
        public static IQueryable<Post> WithDefaultOrdering(this IQueryable<Post> posts)
        {
            return posts.OrderByDescending(p => p.PublishDate);
        }
    }
}